import { login } from '@/services/user';
// import { useCallback, useEffect } from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Form, Input, Menu, message } from 'antd';
import React, { useCallback, useState } from 'react';
import { history } from 'umi';
import styles from './index.less';

const HomePage: React.FC = () => {
  const [form] = Form.useForm();
  const { register }: any = history?.location?.query;
  const [menuKey, setMenuKey] = useState(register ? '1' : '0');
  const [ifReturn, setIfReturn] = useState<boolean>(false);

  const loginRole = useCallback(async () => {
    let values = form.getFieldsValue();
    try {
      await login({
        userName: values.username,
        password: values.password,
      }).then((res) => {
        if (res.disable === '6') {
          message.error('您的申请未审批，请等待管理员审核');
        } else if (res.disable === '7') {
          localStorage.setItem('qs', JSON.stringify(res));
          message.error('您的申请已被退回，请重新申请');
          setIfReturn(true);
        } else {
          if (!localStorage.getItem('color')) {
            localStorage.setItem('color', '#1a7721');
          }
          if (res.role === '1') {
            history.push('/');
          } else {
            history.push('/back');
          }
          if (!localStorage.getItem('qs')) {
            localStorage.setItem('qs', JSON.stringify(res));
          }
          message.success('登录成功！');
        }
      });
    } catch (error) {
      console.log(error);
    }
  }, [form]);

  // 切换登录/注册展示元素
  const menuChange = (e: any) => {
    setMenuKey(e.key);
  };

  // 点击跳转
  const imgPush = () => {
    window.location.reload();
  };
  const loginPush = () => {
    const reg1 = /^(?:(?:\+|00)86)?1\d{10}$/;
    const username = form.getFieldValue('username');
    const password = form.getFieldValue('password');
    const reg2 =
      /^S*(?=\S{9,})(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]/;
    if (reg1.test(username) && reg2.test(password)) {
      loginRole();
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.textTitle}>
        <img
          src={require('@/assets/images/homeImg.png')}
          alt="加载失败"
          onClick={imgPush}
          className={styles.textImg}
        />
        <div className={styles.textStyle}>购物网站</div>
      </div>
      <video
        className={styles.videoStyle}
        src="homePageBackground.mp4"
        autoPlay={true}
        loop={true}
        muted
        width="100%"
      />
      <div className={styles.content}>
        <Menu
          mode="horizontal"
          className={styles.menuStyle}
          onClick={menuChange}
          defaultSelectedKeys={[menuKey]}
        >
          <Menu.Item key={'0'}>登录</Menu.Item>
          <Menu.Item key={'1'}>注册</Menu.Item>
        </Menu>
        {menuKey === '0' ? (
          <div className={styles.loginContent}>
            <Form form={form}>
              <Form.Item
                name="username"
                rules={[
                  { required: true, message: '请输入账号（手机号）!' },
                  {
                    pattern: /^(?:(?:\+|00)86)?1\d{10}$/,
                    message: '请输入规范的手机号码！',
                  },
                ]}
              >
                <Input prefix={<UserOutlined />} placeholder="请输入用户名" />
              </Form.Item>
              <Form.Item
                name="password"
                rules={[
                  { required: true, message: '请输入密码!' },
                  {
                    pattern:
                      /^S*(?=\S{9,})(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]/,
                    message: (
                      <div>
                        <div>长度为9~16个字符</div>
                        <div>必须包含大小写字母，数字或特殊符号任意3项!</div>
                      </div>
                    ),
                  },
                ]}
              >
                <Input type="password" placeholder="请输入密码" prefix={<LockOutlined />} />
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit" onClick={loginPush}>
                  登录
                </Button>
              </Form.Item>
            </Form>
          </div>
        ) : menuKey === '1' ? (
          ifReturn ? (
            <div className={styles.enrollContent}>
              <Button
                onClick={() => {
                  history.push({
                    pathname: '/register&revise',
                    query: { userRole: 'return', lastRoute: '登录注册' },
                  });
                }}
              >
                重新申请商家入驻
              </Button>
            </div>
          ) : (
            <div className={styles.enrollContent}>
              <Button
                onClick={() => {
                  history.push({
                    pathname: '/register&revise',
                    query: { userRole: 'shop', lastRoute: '登录注册' },
                  });
                }}
              >
                商家注册
              </Button>
              <Button
                onClick={() => {
                  history.push({
                    pathname: '/register&revise',
                    query: { userRole: 'buy', lastRoute: '登录注册' },
                  });
                }}
              >
                买家注册
              </Button>
            </div>
          )
        ) : (
          <></>
        )}
      </div>
    </div>
  );
};
export default HomePage;
